﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.OverOrder.Presenter;
using MINERP.BLL.OverOrderBLL;
using MINERP.MODEL.FoundationModel;
using System.Net.Mail;
using System.Net;
using FastReport.Utils;
using System.Xml;
using System.Threading;

using System.IO;
using MINERP.BLL.DisjoinProForOutShop;

namespace MINERP.OverOrder.Forms
{
    public partial class FrmEmaiSys : Form
    {
        public FrmEmaiSys()
        {
            InitializeComponent();
        }
        OverOrderBLL _bll = new OverOrderBLL();
        private void buttonSetSure_Click(object sender, EventArgs e)
        {
            if (txtSmtpServer.Text.Trim() == "")
            {
                MessageBox.Show("邮箱服务器地址不能为空！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            if (txtSendMailBox.Text.Trim() == "")
            {
                MessageBox.Show("邮箱地址不能为空！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            if (txtPwd.Text.Trim() == "" || txtPwdConfirm.Text.Trim() == "" || txtPwdConfirm.Text.Trim() != txtPwdConfirm.Text.Trim())
            {
                MessageBox.Show("两次密码不一致！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (txtTitle.Text.Trim() == "")
            {
                MessageBox.Show("请填写邮件主题！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (txtContent.Text.Trim() == "")
            {
                MessageBox.Show("请填写邮件正文内容！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load("MINERP.OverEmail.XML");
            XmlNode root = xmlDoc.SelectSingleNode("Email");
            XmlNodeList nodeList = root.ChildNodes;
            XmlNode xn=nodeList[0];
            XmlElement xe = (XmlElement)xn;
             xe.SetAttribute("OverSmtpServer",txtSmtpServer.Text.Trim());
             xe.SetAttribute("OverSendMailBox", txtSendMailBox.Text.Trim());
             xe.SetAttribute("OverSendUserName", textBoxUserName.Text.Trim());
             xe.SetAttribute("OverMailPWD", txtPwd.Text.Trim());
             xe.SetAttribute("OverTitle", txtTitle.Text.Trim());
             xe.SetAttribute("OverContext", txtContent.Text.Trim());
             xmlDoc.Save("MINERP.OverEmail.XML");//保存。
             MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
         
            
            //Properties.Settings.Default.OverSmtpServer = txtSmtpServer.Text.Trim();
            //Properties.Settings.Default.OverSendMailBox = txtSendMailBox.Text;
            //Properties.Settings.Default.OverMailPWD = txtPwd.Text;
            //Properties.Settings.Default.OverTitle = txtTitle.Text;
            //Properties.Settings.Default.OverContext = txtContent.Text;
            //Properties.Settings.Default.Save();


        }

        private void tabControlMan_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlMan.SelectedIndex == 1)
            {
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                if (File.Exists(Application.StartupPath + @"\MINERP.OverEmail.XML"))
                {
                    xmlDoc.Load("MINERP.OverEmail.XML");
                    XmlNode root = xmlDoc.SelectSingleNode("Email");
                    XmlNodeList nodeList = root.ChildNodes;
                    XmlNode xn = nodeList[0];
                    XmlElement xe = (XmlElement)xn;


                    txtSmtpServer.Text = xe.GetAttribute("OverSmtpServer");
                    txtSendMailBox.Text = xe.GetAttribute("OverSendMailBox"); ;
                    // txtPwd.Text = xe.GetAttribute("OverMailPWD");
                    txtTitle.Text = xe.GetAttribute("OverTitle");
                    txtContent.Text = xe.GetAttribute("OverContext");
                    textBoxUserName.Text = xe.GetAttribute("OverSendUserName");
                    //txtSmtpServer.Text = Properties.Settings.Default.OverSmtpServer;
                    //txtSendMailBox.Text = Properties.Settings.Default.OverSendMailBox;
                    //txtPwd.Text = Properties.Settings.Default.OverMailPWD;
                    //txtTitle.Text = Properties.Settings.Default.OverTitle;
                    //txtContent.Text = Properties.Settings.Default.OverContext;
                }
                else
                {
                    MessageBox.Show("MINERP.OverEmail.XML文件不存在，请重新安装程序");
                }
            }
            else
            {
                //comboBoxOutShop.DataSource = _bll.GetOutShopList();
                //comboBoxOutShop.DisplayMember = "OutShopName";
                //comboBoxOutShop.ValueMember = "OutShopId";
            }
        }

        private void bbuttonSetCancel_Click(object sender, EventArgs e)
        {
            txtSmtpServer.Text = "";
            txtSendMailBox.Text = "";
            txtPwd.Text = "";
            txtTitle.Text = "";
            txtContent.Text = "";
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonSetClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmEmaiSys_Load(object sender, EventArgs e)
        {
            //comboBoxOutShop.DataSource = _bll.GetOutShopList();
            //comboBoxOutShop.DisplayMember = "OutShopName";
            //comboBoxOutShop.ValueMember = "OutShopId";
         
            checkedListBoxOutShop.DataSource = _bll.GetOutShopList();
            checkedListBoxOutShop.ValueMember = "OutShopId";
            checkedListBoxOutShop.DisplayMember = "OutShopName";

        }
        Thread threadSendMail;
        List<string> SendFailList = new List<string>();
        private void buttonSentMail_Click(object sender, EventArgs e)
        {
            try
            {
                this.textBoxErr.Visible = false;
                this.Cursor = Cursors.WaitCursor;
                textBoxErr.Text = "";
                this.buttonSentMail.Enabled = false;
                // int outShopId=((OutProcessShop_Info)comboBoxOutShop.SelectedItem).OutShopId;
                int outShopId = 0;

                var listItems = checkedListBoxOutShop.CheckedItems;

                int count = listItems.Count;

                if (count != 1)
                {
                    foreach (var list in listItems)
                    {
                        OutProcessShop_Info info = ((OutProcessShop_Info)list);
                        int shopId = info.OutShopId;
                        string shopname = info.OutShopName;
                        // int rtnInt = SendMailByOutShopId(shopId);
                        string para = shopId + "|" + shopname;
                        //ParameterizedThreadStart pts = new ParameterizedThreadStart(SendMailByOutShopId1);
                        //threadSendMail = new Thread(new ParameterizedThreadStart(SendMailByOutShopId1));
                        //threadSendMail.Start(para);
                        SendMailByOutShopId1(para);
                        //if (rtnInt == -2)
                        //{
                        //    //MessageBox.Show("数据为空，邮件未发！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        //    continue;

                        //}
                        //else if (rtnInt == -1)
                        //{
                        //    //MessageBox.Show(shopname + "发送邮件异常，邮件未发！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        //    continue;
                        //}
                        //else
                        //{
                        //    //MessageBox.Show("邮件发送成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        //}
                    }
                    if (SendFailList.Count == 0)
                    {
                        MessageBox.Show("邮件发送成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        this.textBoxErr.Visible = true;
                        string strT = "";
                        foreach (string str in SendFailList)
                        {
                            strT += str + ",";
                        }
                        textBoxErr.Text = strT.TrimEnd(',');

                    }

                }
                else
                {
                    outShopId = ((OutProcessShop_Info)checkedListBoxOutShop.CheckedItems[0]).OutShopId;
                    string shopname = ((OutProcessShop_Info)checkedListBoxOutShop.CheckedItems[0]).OutShopName;
                    int rtnInt = SendMailByOutShopId(outShopId);
                    if (rtnInt == -2)
                    {
                        MessageBox.Show("数据为空，邮件未发！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    }
                    else if (rtnInt == -1)
                    {
                        MessageBox.Show(shopname + "发送邮件异常，请先点击‘邮箱设置’进行配置！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else if (rtnInt == -3)
                    {
                        MessageBox.Show(shopname + "收件邮箱未设置，请在后台设置！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show("邮件发送成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    }
                }
                this.buttonSentMail.Enabled = true;
                this.Cursor = Cursors.Default;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
        }
        public int SendMailByOutShopId(int inOutShopId)
        {
            int OutShopId = (int)inOutShopId;
            DataSet set = _bll.GetAllUnComplateProduct(OutShopId);
            if (set.Tables[0].Rows.Count == 0)
            {
                return -2;
            }
            set.WriteXml(@"C:\WINDOWS\xmlData\OverEmail.xml", XmlWriteMode.WriteSchema);
            FastReport.Report report = new FastReport.Report();
            report.Load(Application.StartupPath + "\\frxOverEmail.frx");
            //report.RegisterData(dt, "deliverOrderInfo");
            report.Prepare();
            FastReport.Export.Xml.XMLExport export = new FastReport.Export.Xml.XMLExport();
            export.AllowOpenAfter = false;
            string mailSendName = DateTime.Now.ToString("yyyyMMddHHmmss");
            string filePath = @"C:\WINDOWS\xmlData\" + mailSendName + ".xls";
            report.Export(export, filePath);


            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load("MINERP.OverEmail.XML");
            XmlNode root = xmlDoc.SelectSingleNode("Email");
            XmlNodeList nodeList = root.ChildNodes;
            XmlNode xn = nodeList[0];
            XmlElement xe = (XmlElement)xn;


            txtSmtpServer.Text = xe.GetAttribute("OverSmtpServer");
            string shopMailAddr = _bll.GetOutShop(inOutShopId).EmailAddress;
            if (shopMailAddr == null||shopMailAddr=="@")
            {
                return -3;
            }
            //string sendMailAddr = Properties.Settings.Default.OverSendMailBox;
            //string smtpServer = Properties.Settings.Default.OverSmtpServer;
            //string pwd = Properties.Settings.Default.OverMailPWD;
            //string title = Properties.Settings.Default.OverTitle;
            //string content = Properties.Settings.Default.OverContext;
            string sendMailAddr = xe.GetAttribute("OverSendMailBox");
            string smtpServer = xe.GetAttribute("OverSmtpServer");
            string pwd = xe.GetAttribute("OverMailPWD");
            string title = xe.GetAttribute("OverTitle");
            string content = xe.GetAttribute("OverContext");
            string UserName = xe.GetAttribute("OverSendUserName");
            string attachMent = filePath;


            string[] sends = sendMailAddr.Split('@');
            SmtpClient client = new SmtpClient(smtpServer);
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential(UserName, pwd);
            MailMessage mmsg = new MailMessage(sendMailAddr, shopMailAddr);
            mmsg.Subject = title;
            mmsg.SubjectEncoding = Encoding.UTF8;
            mmsg.Body = content;
            mmsg.BodyEncoding = Encoding.UTF8;
            mmsg.IsBodyHtml = true;
            mmsg.Priority = MailPriority.High;
            mmsg.Attachments.Add(new Attachment(attachMent));
            try
            {
                client.Send(mmsg);
                //MessageBox.Show("邮件发送成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
              
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return -1;
            }
            mmsg.Dispose();
            report.Dispose();
            return 0;
        }
        DisJoinBLL2_Fuji dsbll = new DisJoinBLL2_Fuji();

        public void  SendMailByOutShopId1(object inOutShop)
        {
            int OutShopId = Convert.ToInt32(((string)(inOutShop)).Split('|')[0]);

            string outShopName = ((string)(inOutShop)).Split('|')[1];
            DataSet set = _bll.GetAllUnComplateProduct(OutShopId);
            if (set.Tables[0].Rows.Count == 0)
            {
                return ;
            }
            set.WriteXml(@"C:\WINDOWS\xmlData\OverEmail.xml", XmlWriteMode.WriteSchema);
            FastReport.Report report = new FastReport.Report();
            report.Load(Application.StartupPath + "\\frxOverEmail.frx");
            //report.RegisterData(dt, "deliverOrderInfo");
            report.Prepare();
            FastReport.Export.Xml.XMLExport export = new FastReport.Export.Xml.XMLExport();
            export.AllowOpenAfter = false;
            string mailSendName = DateTime.Now.ToString("yyyyMMddHHmmss");
            string filePath = @"C:\WINDOWS\xmlData\" + mailSendName + ".xls";
            report.Export(export, filePath);


            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load("MINERP.OverEmail.XML");
            XmlNode root = xmlDoc.SelectSingleNode("Email");
            XmlNodeList nodeList = root.ChildNodes;
            XmlNode xn = nodeList[0];
            XmlElement xe = (XmlElement)xn;

            
            txtSmtpServer.Text = xe.GetAttribute("OverSmtpServer");
            string shopMailAddr = dsbll.GetOutShopEmail(OutShopId);
            if (shopMailAddr == null || shopMailAddr == "@")            
            {
                SendFailList.Add(outShopName);
                File.Delete(filePath);
                return ;
            }
            //string sendMailAddr = Properties.Settings.Default.OverSendMailBox;
            //string smtpServer = Properties.Settings.Default.OverSmtpServer;
            //string pwd = Properties.Settings.Default.OverMailPWD;
            //string title = Properties.Settings.Default.OverTitle;
            //string content = Properties.Settings.Default.OverContext;
            string sendMailAddr = xe.GetAttribute("OverSendMailBox");
            string smtpServer = xe.GetAttribute("OverSmtpServer");
            string pwd = xe.GetAttribute("OverMailPWD");
            string title = xe.GetAttribute("OverTitle");
            string content = xe.GetAttribute("OverContext");
            string attachMent = filePath;


            string[] sends = sendMailAddr.Split('@');
            SmtpClient client = new SmtpClient(smtpServer);
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential(sends[0], pwd);
            MailMessage mmsg = new MailMessage(sendMailAddr, shopMailAddr);
            mmsg.Subject = title;
            mmsg.SubjectEncoding = Encoding.UTF8;
            mmsg.Body = content;
            mmsg.BodyEncoding = Encoding.UTF8;
            mmsg.IsBodyHtml = true;
            mmsg.Priority = MailPriority.High;
            mmsg.Attachments.Add(new Attachment(attachMent));
            try
            {
                client.Send(mmsg);
                //MessageBox.Show("邮件发送成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                SendFailList.Add(outShopName);
                return;
            }
            finally
            {
                mmsg.Dispose();
                report.Dispose();
                File.Delete(filePath);
            }

            
          
            return ;
        }

        private void buttonAll_Click(object sender, EventArgs e)
        {
            int count=checkedListBoxOutShop.Items.Count;
            for (int i = 0; i < count; i++)
            {
                checkedListBoxOutShop.SetItemChecked(i, true);
 //checkedListBoxOutShop.
            }
          
        }

        private void buttonNone_Click(object sender, EventArgs e)
        {
            int count = checkedListBoxOutShop.Items.Count;
            for (int i = 0; i < count; i++)
            {
                if (checkedListBoxOutShop.GetItemChecked(i))
                {
                    checkedListBoxOutShop.SetItemChecked(i, false);
                }
                else
                {
                    checkedListBoxOutShop.SetItemChecked(i, true);
                }
                
            }
        }
        
    }
}
